package org.kzwl.service.app.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.monitorjbl.xlsx.StreamingReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.ResponseData;
import org.kzwl.comm.pojo.bo.book.BookQueryBasic;
import org.kzwl.comm.pojo.bo.book.BooksBasicBO;
import org.kzwl.comm.pojo.bo.book.QueryTitleBO;
import org.kzwl.comm.pojo.bo.comment.QueryCommentBO;
import org.kzwl.comm.pojo.dto.book.*;
import org.kzwl.comm.pojo.dto.comment.CommentDTO;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.entity.app.*;
import org.kzwl.entity.web.CuData;
import org.kzwl.mapper.app.BookMapper;
import org.kzwl.mapper.app.BookUserMapper;
import org.kzwl.mapper.app.CategoryMapper;
import org.kzwl.mapper.app.CommentMapper;
import org.kzwl.service.app.BookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.service.app.CommentService;
import org.kzwl.service.web.CuDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-09-10
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BookUserMapper bookUserMapper;

    @Autowired
    private CommentService commentService;

    @Autowired
    CuDataService cuDataService;

    @Override
    public ResponseData<Void> saveTest() {
        System.out.println("---------------");

        return new ResponseData<>();
    }

    //region 编辑推荐
    @Override
    public List<Book> recommend() {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Book::getCuBookRecommend, 1).orderByDesc(Book::getCuBookUpdateDate).last(" limit 6");
        List<Book> list = bookMapper.selectList(queryWrapper);
        for (Book book : list) {
            book.setCuBookAbbreviation(Consts.MyConsts.IMGURLPATH + book.getCuBookAbbreviation());
        }
        return list;
    }
    //endregion

    //region 热门榜单与每日新书
    @Override
    public HotOrNewDTO hotOrNew() {
        HotOrNewDTO dto = new HotOrNewDTO();
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        //region 查询热门
        queryWrapper.lambda().orderByDesc(Book::getCuBookScore).last(" limit 3");
        List<Book> hotList = bookMapper.selectList(queryWrapper);
        List<BookDTO> hotDtoList = JSONArray.parseArray(JSON.toJSONString(hotList), BookDTO.class);
        dto.setHotList(hotDtoList);
        //endregion
        return dto;
    }
    //endregion

    //region 每日新书

    @Override
    public HotOrNewDTO NewBooks() {
        HotOrNewDTO dto = new HotOrNewDTO();
        //region 每日新书
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Book::getCuBookCreateDate).last(" limit 8");
        List<Book> newList = bookMapper.selectList(queryWrapper);
        List<BookDTO> newDtoList = JSONArray.parseArray(JSON.toJSONString(newList), BookDTO.class);
        dto.setNewList(newDtoList);
        //endregion
        return dto;
    }

    //endregion

    //region 根据分类查询
    @Override
    public IPage<BookDTO> queryBookByType(BookQueryBasic bo) {
        IPage<Book> page = new Page<>();
        page.setCurrent(bo.getCurrent());
        page.setSize(bo.getSize());
        List<BookDTO> list = new ArrayList<>();
        Category category = categoryMapper.selectById(bo.getCuBookCategoryId());
        if (category.getCuCategoryParent() == 0) {
            List<Book> books = bookMapper.queryType(category.getCuCategoryId(), ((bo.getCurrent() - 1) * bo.getSize()), bo.getSize());
            Integer integer = bookMapper.queryTypeCount(category.getCuCategoryId(), ((bo.getCurrent() - 1) * bo.getSize()), bo.getSize());
            page.setTotal(integer);
            list = JSONArray.parseArray(JSONObject.toJSONString(books), BookDTO.class);
        } else {
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Book::getCuBookCategoryId, bo.getCuBookCategoryId()).orderByDesc(Book::getCuBookScore);
            page = bookMapper.selectPage(page, queryWrapper);
            list = JSONArray.parseArray(JSON.toJSONString(page.getRecords()), BookDTO.class);
        }
        list.forEach(l -> {
            l.setCuCategoryName(category.getCuCategoryName());
        });

        IPage<BookDTO> result = new Page<>();
        BeanUtils.copyProperties(page,result);
        result.setRecords(list);
        return result;
    }
    //endregion

    //region 查询书籍详情
    @Override
    public BookDetailsDTO getBook(BookQueryBasic bo) {
        BookDetailsDTO detailsDTO = new BookDetailsDTO();
        Book book = bookMapper.selectById(bo.getCuBookId());
        if (book == null) {
            throw new BizException("书籍信息有误");
        }

        BeanUtils.copyProperties(book, detailsDTO);

        //region 查询当前用户是否看过这本书
        QueryWrapper<BookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BookUser::getCuUserId, bo.getCuUserId()).eq(BookUser::getCuBookId, bo.getCuBookId()).last(" limit 1");
        BookUser result = bookUserMapper.selectOne(queryWrapper);
        if (result != null) {
            detailsDTO.setCuBookUserContinue(result.getCuBookUserContinue());
        }
        //endregion

        //region 查询评论(十条)
        QueryCommentBO queryBO = new QueryCommentBO();
        queryBO.setCurrent(1);
        queryBO.setSize(10);
        queryBO.setCuExtId(bo.getCuBookId());
        queryBO.setCuUserId(bo.getCuUserId());
        List<CommentDTO> commentDTOS = commentService.queryComment(queryBO);
        detailsDTO.setComments(commentDTOS);
//        String substring = detailsDTO.getCuBookAddress().substring(detailsDTO.getCuBookAddress().indexOf("/"));
//        detailsDTO.setCuBookAddress(substring);
        //endregion

        //region 查询分类
        List<BookCategoryDTO> categoryDTO = MyUtils.getCategoryDTO(detailsDTO.getCuBookAddress());
        detailsDTO.setCategory(categoryDTO);
        if (categoryDTO != null && categoryDTO.size() > 0) {
            if (detailsDTO.getCuBookUserContinue() == null) {
                detailsDTO.setPrevious(categoryDTO.get(0).getCuBookCategoryName());
            } else {
                BookCategoryDTO first = categoryDTO.stream().filter(c -> c.getCuBookContinue() >= Integer.parseInt(detailsDTO.getCuBookUserContinue() + "")).findFirst().get();
                detailsDTO.setPrevious(first.getCuBookCategoryName());
            }
        }
        //endregion
        detailsDTO.setCuBookAddress(Consts.MyConsts.URLPATH + detailsDTO.getCuBookAddress());

        if (detailsDTO.getCuBookUserContinue() == null) {
            detailsDTO.setCuBookUserContinue(1);
        }
        return detailsDTO;
    }
    //endregion

    //region 热门搜索
    @Override
    public List<BookDTO> getHot() {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        //region 查询热门
        queryWrapper.lambda().orderByDesc(Book::getCuBookPopularity).last(" limit 8");
        List<Book> hotList = bookMapper.selectList(queryWrapper);
        List<BookDTO> hotDtoList = JSONArray.parseArray(JSON.toJSONString(hotList), BookDTO.class);
        //endregion
        return hotDtoList;
    }
    //endregion

    //region 关键搜索
    @Override
    public List<BookDTO> queryTitle(QueryTitleBO bo) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(Book::getCuBookName,bo.getSearch());
        IPage<Book> page = new Page<>();
        page.setCurrent(bo.getCurrent()).setSize(bo.getSize());
        page = bookMapper.selectPage(page,queryWrapper);
        List<BookDTO> list = JSONObject.parseArray(JSONObject.toJSONString(page.getRecords()), BookDTO.class);
        return list;
    }
    //endregion

    //region 同步数据
    @Override
    public void syncBook() {
        String filePath = "C:\\Users\\Administrator\\Desktop\\pdf\\32万目录.xlsx";
//        String columns[] = {"id", "一级名称", "二级名称", "书名", "作者", "出版社", "isbn", "日期", "封面路径", "文件路径"};
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Workbook workbook = StreamingReader.builder()
                .rowCacheSize(100)//一次读取多少行(默认是10行)
                .bufferSize(1024)//使用的缓冲大小(默认1024)
                .open(in);
        int i = 0;
        for (Sheet sheet : workbook) {
            for (Row row : sheet) {
//                System.out.println("分类" + row.getCell(1).getStringCellValue());
                if (!row.getCell(1).getStringCellValue().equals("一级名称")) {
                    QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(Category::getCuCategoryName, row.getCell(1).getStringCellValue());
                    Category category = categoryMapper.selectOne(queryWrapper);
                    if (category == null) {
                        category = new Category();
                        category.setCuCategoryName(row.getCell(1).getStringCellValue());
                        category.setCuCategoryParent(1);
                        categoryMapper.insert(category);
                    }
//                System.out.println("书名" + row.getCell(3).getStringCellValue());
//                System.out.println("作者" + row.getCell(4).getStringCellValue());
//                System.out.println("出版社" + row.getCell(5).getStringCellValue());
                    String a = row.getCell(8).getStringCellValue();
                    StringBuffer str = new StringBuffer(a);
                    a = str.insert(a.indexOf("/"), "11").toString();
//                System.out.println("封面路径" + a);
                    String b = row.getCell(9).getStringCellValue();
                    str = new StringBuffer(b);
                    b = str.insert(b.indexOf("/"), "11").toString();
//                System.out.println("文件路径" + b);
                    Book book = new Book();
                    book.setCuBookName(row.getCell(3).getStringCellValue());
                    book.setCuBookPress(row.getCell(5).getStringCellValue());
                    book.setCuBookCategoryId(category.getCuCategoryId());
                    book.setCuBookAuthor(row.getCell(4).getStringCellValue());
                    book.setCuBookAbbreviation(a);
                    book.setCuBookAddress(b);
                    FileInputStream fis = null;
                    File file = null;
                    file = new File(Consts.MyConsts.PDFPATH + b);
                    PDDocument doc = null;
                    try {
                        fis = new FileInputStream(file);
                        PDFParser parser = new PDFParser(new RandomAccessBuffer(fis));
                        parser.parse();
                        doc = parser.getPDDocument();
                        book.setCuBookPages(doc.getNumberOfPages());
                        bookMapper.insertMy(book);
                    } catch (Exception e) {
                        System.out.println("系统找不到指定的文件:"+file.getPath());
                        book.setCuBookPages(100);
                        book.setCuBookLabel(1);
                        bookMapper.insertMy(book);
                    }
                }
                i++;
                if (i > 100) {
                    System.err.println("现在i是----"+i);
                }
            }
        }
    }

    //endregion
    public static void main(String[] args) {
        FileInputStream fis = null;
        File file = null;
        file = new File(Consts.MyConsts.PDFPATH +"B");
        try {
            fis = new FileInputStream(file);
            PDFParser parser = new PDFParser(new RandomAccessBuffer(fis));
            PDDocument doc = null;
            parser.parse();
            doc = parser.getPDDocument();
        } catch (Exception e) {
            System.out.println();
        }
    }
}
